//
//  WBOAuthController.swift
//  SwiftWeibo
//
//  Created by Lausen on 2017/4/17.
//  Copyright © 2017年 id. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBOAuthController: UIViewController {

    /// 懒加载一个webView
    fileprivate lazy var webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        
        ///设置webView的背景颜色
        webView.backgroundColor = UIColor.white
        
        ///设置webView是否可以滚动
        webView.scrollView.isScrollEnabled = false
        
        title = "登录SwiftWeiBo"
        
        view.backgroundColor = UIColor.white
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
     
        //设置item
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
        
        /// 授权界面的网址
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirect_url)"
        
        guard let url = URL(string: urlString) else{
            
            return
        }
        
        let request = URLRequest(url: url)
        
        webView.loadRequest(request)
        
        webView.delegate = self

    }
    
    @objc fileprivate func close (){
        
        SVProgressHUD.dismiss()
    
        dismiss(animated: true, completion: nil)
    }
    
    
    /// 自动填充用户名和密码 webView的注入,直接通过js修改本地浏览器缓存的页面内容
    @objc private func autoFill(){
        //15375098610
        let js = "document.getElementById('userId').value = '735414313@qq.com';" + "document.getElementById('passwd').value = '18949933685liu';"
        
        webView.stringByEvaluatingJavaScript(from: js)
    }
}


// MARK: - UIWebViewDelegate
extension WBOAuthController: UIWebViewDelegate{
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if request.url?.absoluteString.hasPrefix(WBRedirect_url) == false {
            
            return true
        }
        
        if request.url?.query?.hasPrefix("code=") == false {
            
            print("取消了授权")
            
            //如果取消了,就应该返回到上一级控制器
            close()
            
            return false
        }
        
        ///如果连接里面含有baidu.就证明回调成功了
        print("请求的连接\(request.url?.absoluteString)")
        
        print("包含了code\(request.url?.query)")
        
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        print("授权码\(code)")
        
        WBNetworkManager.shared.loadAccess_token(code: code) { (isSuccess) in
            
            if !isSuccess{
                
                SVProgressHUD.showError(withStatus: "网络错误")
            }else{
                
                SVProgressHUD.showSuccess(withStatus: "登录成功")
                
                //1:放回到上一个界面,并刷新数据
                //利用通知去做这个
                NotificationCenter.default.post(
                    name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification),
                    object: nil)
                
                //2:关闭界面
                self.close()
            }
        }
        
        return false
    }
    
    /// 网页开始加载时调用的方法
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    /// 网页结束加载时调用的方法
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
}
